import React ,{useState,useEffect,useMemo ,useRef,useImperativeHandle } from "react";
import { ComponentsMap } from "@/config/index.ts";
import _ from 'lodash';
import { Form } from "antd";

const formItemLayout = {
    labelCol: {
      xs: { span: 24 },
      sm: { span: 6 },
    },
    wrapperCol: {
      xs: { span: 24 },
      sm: { span: 14 },
    },
  };

interface FormDataProps<T> {
    schema:Array<T>;
    model:Object
}

const DynamicForm: React.FC<FormDataProps<T>> =  React.forwardRef(({schema,model},ref) => {
    const [form] = Form.useForm();
    const [formModel,setFormModel] = useState(model);
    const [formSchema,setFormSchema] = useState([]);


    useImperativeHandle(ref,()=>({
        validateFieldsFn: ()=> validateFields(),
        resetFieldsFn: ()=> resetFields(),
    }))
    const initForm = () => {
        const propsMapschema = _.map(schema,(value:any,key:string)=>{
            return {...value}
        }); 
        setFormSchema(propsMapschema);
    }
    useEffect(()=>{
        initForm()
        form.setFieldsValue(model)
        console.log(formSchema,'-----------formSchema');
        
    },[])
    // 表单验证
    const validateFields = () => {
        return new Promise((resolve, reject) => {
            form
            .validateFields()
            .then((formData:FormDataProps<T>["model"]) => {
                console.log(formData,'---formData++')
                resolve(formData);
            })
            .catch((err) => reject(err));
        });
    };
    // 表单重置
    const resetFields = (isInit = true) => {
        // 是否清空默认值
        if (isInit) {
            setFormModel({})
        }
        form.resetFields();
    };
    return (
        <Form form={form}  {...formItemLayout} style={{ maxWidth: 600 }} autoComplete="off">
            {
                 _.map(formSchema,(item:any,key:string)=>{
                    return <Form.Item label={item.label} name={item.name} key={item.name} {...item.formItemProps} >
                            {ComponentsMap[item.component](item.componentProps)}
                        </Form.Item>
                    
                })
            }
        </Form>
    )
})


export default DynamicForm